<template>
  <div id="locations" class="body-container">
    <!--头部地址选择-->
    <div class="top-banner">
      <div class="location-wrapper">
        <span class="location-label">所在城市</span>
        <div class="location-addr-wrapper" @click="regionSelectorControl">
          <span class="location-list">{{locationName}}</span>
          <em class="dropdown-arrow"><span class="arrow-down"></span></em>
        </div>
      </div>
    </div>
    <!--body中的店面地址列表-->
    <div class="content-wrapper">
      <div class="store-title"><span class="icon icon-store"></span>免费扫描店面</div>
      <div class="store-items-wrapper">
        <ul class="store-items-ul">
          <li class="store-item" v-for="store in storeArray">
            <TableItem :image="store.shopImage" :title="store.name" :subDetailOne="'地址:'+store.address" :subDetailTwo="'电话:'+store.tel" v-on:itemClicked="goAppoint(store.id)"></TableItem>
          </li>
        </ul>
        <!--需要申请开通界面-->
        <div class="no-store-wrapper" v-if="noStore">
          <div class="no-store-tips">
            <span>您所在的城市还未开通免费扫描服务，点击申请开通，凑够500个申请，我们就会在您的城市开通。</span>
          </div>
          <button class="btn" @click="applyCityOpen">申请开通</button>
        </div>
        <loading :appear="loading"></loading>
      </div>
    </div>
    <!--城市选择弹窗-->
    <div class="layout-mask" v-if="showRegionSelector" @click="regionSelectorControl">
        <RegionSelector :show="regionOpen" :locationCode="locationCode" v-on:selectorWillClose="regionSelectorClose" v-on:selectorClose="regionSelectorControl" v-on:finishedCitySelector="showSelectedCity(arguments[0],arguments[1])"></RegionSelector>
    </div>
    <!--提示语弹框-->
    <div class="layout-mask" v-if="alertShow" @click="alertDismiss">
      <Prompt :show="alertDialogShow" :options="alertDialogOpt" v-on:closed="alertDismiss" v-on:confirm="confirm" :btnCounts="btnCounts" v-on:afterLeave="alertDialogClose"></Prompt>
    </div>
  </div>
</template>

<script>
import Config from 'common/script/config.js'
import TableItem from 'components/tableItem/tableItem'
import RegionSelector from 'components/regionSelector/regionSelector'
import Loading from 'components/loading/loading'
import Prompt from 'components/prompt/prompt'
import wx from 'wx'

var LOCAL_DEBUG = false

var bottons = []
bottons['OK'] = {'text': '分享到朋友圈'}
// bottons['OK'] = {'text': '确认'}
// bottons['Cancel'] = {'text': '取消'}
export default {
  name: 'locations',
  components: {
    TableItem,
    RegionSelector,
    Loading,
    Prompt
  },
  data () {
    return {
      loading: true,
      alertShow: false,
      alertDialogShow: false,
      showRegionSelector: false,
      regionOpen: false,
      locationCode: 0,
      locationName: '正在定位...',
      userLatitude: 38.917268, // 用户维度
      userLongitude: 121.593292, // 用户经度
      newLocation: false,
      storeArray: [],
      noStore: false,
      openId: 0,
      userId: 0,
      btnCounts: 1,
      alertDialogOpt: {
        title: '提示',
        msg: '恭喜您是"大连"第351位申请此项目服务，发到朋友圈，让更多朋友申请，凑齐500个就开通这个服务。',
        bottons: bottons
      }
    }
  },
  methods: {
    regionSelectorControl: function () {
      if (this.regionOpen) {
        this.regionOpen = false
      } else {
        this.showRegionSelector = true
        this.regionOpen = true
      }
    },
    // 区域选择框关闭
    regionSelectorClose: function () {
      this.showRegionSelector = false
      this.loading = true
      this.storeAddressByLocationCode(this.locationCode)
    },
    showSelectedCity: function (code, name) {
      this.locationCode = code
      this.locationName = name
    },
    regionByGPS: function (latitude, longitude) {
      this.$http.post('/freescan/free/region', {
        'latitude': latitude,
        'longitude': longitude
      }).then((response) => {
        response = response.body
        this.locationCode = response.code
        this.locationName = response.fullName
        this.storeAddressByLocationCode(this.locationCode)
      })
    },
    storeAddressByLocationCode: function (code) {
      this.hasLocation = true
      this.noStore = false
      this.$http.post('/freescan/free/getAddresses', {
        'code': code
      }).then((response) => {
        this.storeArray = response.body
        this.loading = false
        if (this.storeArray.length === 0) {
          this.noStore = true
        }
        console.log(this.storeArray)
      })
    },
    // 跳转到店面的预约界面
    goAppoint: function (storeId) {
      window.location.href = 'appoint.html?storeId=' + storeId + '&userId=' + this.userId + '&openId=' + this.openId
    },
    // 申请城市开通扫描服务
    applyCityOpen: function () {
      // this.alertShow = true
      // this.alertDialogShow = true
      this.loading = true
      this.$http.post('/freescan/appointment/apply', {
        'openId': this.openId,
        'userId': this.userId,
        'cityCode': this.locationCode
      }).then((response) => {
        response = response.body
        if (response.code === 1) {
          this.alertDialogOpt.msg = '恭喜您是"' + this.locationName + '"第' + response.body + '位申请此项目服务，发到朋友圈，让更多朋友申请，凑齐500个就开通这个服务。'
          this.btnCounts = 1
        } else if (response.code === 2) {
          console.log('code is 2')
          this.alertDialogOpt.msg = '您已成功申请"' + this.locationName + '"的此项目服务，发到朋友圈，让更多朋友申请，凑齐500个就开通这个服务。'
          this.btnCounts = 1
        } else {
          this.alertDialogOpt.msg = '申请失败'
          this.btnCounts = 0
        }
        this.alertShow = true
        this.alertDialogShow = true
        this.loading = false
        console.log(response)
      })
    },
    alertDismiss: function () {
      this.alertDialogShow = false
    },
    confirm: function () {
      this.alertDialogShow = false
    },
    alertDialogClose: function () {
      this.alertShow = false
    }
  },
  created: function () {
    this.openId = Config.getReqParam('wechatid')
    this.userId = Config.getReqParam('userid')
    if (LOCAL_DEBUG) {
      this.regionByGPS(this.userLatitude, this.userLongitude)
    }
    if (!LOCAL_DEBUG) {
      var _this = this
      this.$http.post('/freescan/wechat/jsSignature', {
        'openid': this.openId,
        'userid': this.userId
      }).then((response) => {
        response = response.body
        wx.config({
          debug: LOCAL_DEBUG,
          appId: response.appid, // 必填，公众号的唯一标识
          timestamp: response.timestamp, // 必填，生成签名的时间戳
          nonceStr: response.noncestr, // 必填，生成签名的随机串
          signature: response.signature, // 必填，签名，见附录1
          jsApiList: ['openLocation', 'getLocation'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
        })
        wx.ready(function () {
          // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
          wx.getLocation({
            type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
            success: function (res) {
                var latitude = res.latitude // 纬度，浮点数，范围为90 ~ -90
                var longitude = res.longitude // 经度，浮点数，范围为180 ~ -180。
                var speed = res.speed // 速度，以米/每秒计
                var accuracy = res.accuracy // 位置精度
                console.log(latitude, longitude, speed, accuracy)
                _this.regionByGPS(latitude, longitude)
                // alert('纬度:' + latitude)
                // alert('经度:' + longitude)
            }
          })
        })
      })
    }
  }
}

if (!LOCAL_DEBUG) {
}

</script>

<style lang="stylus" rel="stylesheet/stylus">
@import '../../common/stylus/mixin'
  .content-wrapper
    position relative
    padding-top 41px
    box-sizing border-box
    .store-title
      position absolute
      width 100%
      top 0
      height 40px
      line-height 40px
      padding-left 15px
      font-size 14px
      border-bottom 1px solid #dcdcdc
      box-sizing border-box
      .icon-store
        display block
        float left
        color #ff850a
        padding-top 11px
        padding-right 10px
        font-size 17px
    .store-items-wrapper
      position relative
      height 100%
      width 100%
      overflow-x hidden
      overflow-y auto
      .store-items-ul
        margin 0px
        padding 0px
        .store-item
          display block
      .no-store-wrapper
        position relative
        font-size 18px
        color #413e4d
        .no-store-tips
          padding 30px 40px
          border-1px(#dcdcdc)
</style>
